package com.jielin.handling.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;



public class JacksonUtil {

	
	/**
	 * json转java对象
	 * @param args
	 */
	public static <T> T json2Obj(String json,Class<T> t) {
		ObjectMapper objectMapper = new ObjectMapper();
		T obj = null;
		try {
			obj = objectMapper.readValue(json, t);
			System.out.println("readJson2Entity="+obj);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return obj;
	}
	
	/**
	 * java对象转json
	 * @param args
	 */
	public static String obj2Json(Object obj) {
		ObjectMapper objectMapper = new ObjectMapper();
		String json = null;
		try {
			json = objectMapper.writeValueAsString(obj);
		} catch (JsonGenerationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("obj2Json="+json);
		return json;
	}
	/**
	 * json字符串装list
	 * @param jsonString
	 * @param t
	 * @return
	 */
	public static List json2List(String jsonString,Class t){
		ObjectMapper mapper = new ObjectMapper(); 
		JavaType javaType = mapper.getTypeFactory().constructParametricType(ArrayList.class, t);
		try {
		return mapper.readValue(jsonString, javaType);
		}catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	
	}

	/**	/**
	 * list转Json
	 * @param jsonString
	 * @return
	 */
	public static String list2Json(List list){
		ObjectMapper mapper = new ObjectMapper(); 
		try {
			return mapper.writeValueAsString(list);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}  
	}
}
